﻿namespace GSC.WebControls
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Web;
    using System.IO;
	public class AjaxFileUploadModule : IHttpModule
	{
		public void Init(HttpApplication context)
		{
			context.PreSendRequestHeaders += new EventHandler(PreSendRequestHeadersHandler);
		}

		private void PreSendRequestHeadersHandler(object sender, EventArgs e)
		{
			HttpApplication application = (HttpApplication)sender;
			HttpResponse response = application.Response;

			if (response.StatusCode == 302 && 
				AjaxFileUploadUtility.IsInIFrameAsyncPostBack(application.Request.Params))
			{
				string redirectLocation = response.RedirectLocation;
				List<HttpCookie> cookies = new List<HttpCookie>(response.Cookies.Count);

				for (int i = 0; i < response.Cookies.Count; i++)
				{
					cookies.Add(response.Cookies[i]);
				}

				response.ClearContent();
				response.ClearHeaders();

				for (int i = 0; i < cookies.Count; i++)
				{
					response.AppendCookie(cookies[i]);
				}

				response.Cache.SetCacheability(HttpCacheability.NoCache);
				response.ContentType = "text/plain";

				AjaxFileUploadUtility.WriteScriptBlock(response, true);
				
				StringBuilder sb = new StringBuilder();
				TextWriter writer = new StringWriter(sb);
				AjaxFileUploadUtility.EncodeString(writer, "pageRedirect", String.Empty, redirectLocation);
				response.Write(sb.Replace("*/", "*//*").ToString());

				AjaxFileUploadUtility.WriteScriptBlock(response, false);

				response.End();
			}
		}

		public void Dispose() {}
	}
}
